const wx2my = require('../../wx2my');

// pages/select_car/select_car.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    auth: 1,
    appCode: '',
    list: [],
    wrap: true,
    acceptRule: true,
    openAgain: 'openAgain',
    impower: 'impower',
    endDisinfect: 'endDisinfect',
    onOff: 0,
    packIndex: 0,
    trade_id: '',
    marker: '',
    id: '',
    device: '',
    foregift_id: '',
    model: 'open_timeout',
    rfid: '',
    goods_id: '',
    rentServiceText: '',
    num: 1,
    minusStatus: 'disable',
    minusStatus1: 'normal',

    itemPrice: '1',
    packId:"0",
    itemMinute: '0.1',
    itemTitle: '',

    maxNum: 1
  },
  onLoad: function (e) {
    if (e.macno) {
      this.setData({
        macno: e.macno
      });
    }

    if (e.rfid) {
      this.setData({
        rfid: e.rfid
      });
    }

    if (e.marker) {
      this.setData({
        marker: e.marker
      });
    }

    this.get_phoneSwitch();
  },
  onReady: function () {
    setTimeout(() => {
      this.permiss();
    }, 200);
    this.get_status();
    this.get_phone();
    this.get_rentService();
    this.get_list();
    this.setData({
      model: 'playTip'
    });
  },
  onShow: function () {
    let that = this;

    if (that.data.foregift_id) {
      that.setData({
        trade_id: that.data.foregift_id
      });
      that.get_pull();
    }
  },

  //手机号是否开启权限
  get_phoneSwitch() {
    let that = this;
    app.wxRequest('get_auth_phone', {}, function (res) {
      if (res.data.code == 1) {
        that.setData({
          auth: res.data.data.auth
        });
      }
    });
  },

  //微信是否启用信用授权权限
  get_status() {
    let that = this;
    app.wxRequest('get_credit', {}, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        if (res.data.data.wx_credit == 0) {
          that.setData({
            mode: true
          });
        } else {
          that.setData({
            mode: false
          });
        }

        that.setData({
          wx_credit: res.data.data.wx_credit
        });
      }
    });
  },

  get_rentService() {
    let that = this;
    app.wxRequest('rentService2', {
      'macno': that.data.macno ? that.data.macno : ''
    }, function (res) {
      that.setData({
        rentServiceText: JSON.parse(res.data.data.val).text
      });
    });
  },

  get_phone() {
    let that = this;
    app.wxRequest('customer', {
      'type': 3
    }, function (res) {
      that.setData({
        tel: res.data.data.tel
      });
    });
  },

  phone() {
    let that = this;
    wx2my.showModal({
      title: '温馨提示',
      content: '拨打电话:' + that.data.tel,

      success(res) {
        if (res.confirm) {
          wx2my.makePhoneCall({
            phoneNumber: that.data.tel
          });
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }

    });
  },

  //是否绑定 手机号 
  permiss(e) {
    let that = this;
    app.wxRequest('profile', {}, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        if (res.data.data.account == '' && that.data.auth == 1) {
          //未绑定
          console.log(res.data.data.account);
          that.setData({
            wrap: false
          }); // if (wx.getStorageSync('wrap') == true) {
          //   that.setData({
          //     wrap: true
          //   });
          // } else {
          //   that.setData({
          //     wrap: false
          //   });
          // }
        }

        if (!that.data.appCode) {
          wx.login({
            success: function (e) {
              console.log(e);
              that.setData({
                appCode: e.code
              });
            }
          });
        }
      } else {
        wx2my.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 2000
        });
      }
    });
  },

  bindPhone(msg) {
    var that = this;
    // let encryptedData = JSON.parse(msg);
    app.wxRequest('get_user_phone', {
      'type': 'ali',
      // 'encryptedData': msg.response,
      'encryptedData': encodeURIComponent(msg.response),

    }, function (res) {
      console.log(res);

      if (res.data.code = 1) {
        let userInfo = res.data.data ? JSON.parse(res.data.data) : '';
        console.log(userInfo, "asdfgasdfasdgasdgasdg");

        if (!userInfo) {
          app.toast('手机号获取失败,请重新获取');
        } else {
          app.wxRequest('edit', {
            'account': userInfo
          }, function (res) {
            console.log(res);

            if (res.data.code == 1) {
              that.setData({
                wrap: true
              });
              wx2my.setStorageSync('wrap', true);
            } else if (res.data.code == -1005) {
              app.toast(res.data.msg);
              that.setData({
                wrap: true
              });
              wx2my.setStorageSync('wrap', true);
            }
          });
        }
      } else {
        app.toast(res.data.msg);
      }
    });
  },


  //绑定微信手机号
  getPhoneNumber(e) {
    console.log(e);
    let that = this;

    my.getPhoneNumber({
      success: (res) => {
        that.setData({
          wrap: true
        });
        console.log('res: ', res);
        let encryptedData = JSON.parse(res.response);
        console.log('getPhone-suc: ', encryptedData);
        that.bindPhone(encryptedData);
        // my.request({
        //     url: '你的后端服务端',
        //     data: encryptedData,
        // });
      },
      fail: (res) => {
        that.setData({
          wrap: true
        });
        console.log('getPhone-err: ', res);
        

        wx2my.showModal({
          title: '提示',
          content: '取消授权，可能会使部分服务无法使用，或页面信息显示不完整',
    
          success(res) {
            if (res.confirm) {
              that.setData({
                wrap: false
              });

              

            } else if (res.cancel) {

             
            }
          }
    
        });

      },
    });


    // if (e.detail.errMsg == 'getPhoneNumber:ok') {
    //   let that = this;
    //   let msg = e;
    //   that.bindPhone(msg);
    // } else {
    //   app.toast('请绑定手机号');
    // }
  },

  // //绑定微信手机号
  // getPhoneNumber(e) {
  //   console.log(e);

  //   if (e.detail.errMsg == 'getPhoneNumber:ok') {
  //     let that = this;
  //     let msg = e;
  //     that.bindPhone(msg);
  //   } else {
  //     app.toast('请绑定手机号');
  //   }
  // },

  get_list() {
    let that = this;
    app.wxRequest('rentToyCar', {
      'token': wx2my.getStorageSync('token'),
      'macno': that.data.macno ? that.data.macno : '',
      'rfid': that.data.rfid ? that.data.rfid : '',
      'marker': that.data.marker
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let list = res.data.data;
        list.forEach((item, index) => {
          item._index = index;
          item.electric = parseFloat(item.electric);
          item.electricity_warning = parseFloat(item.electricity_warning);
        });
        console.log(list);
        that.setData({
          list: list,
          device: list[0].device_id,
          maxNum: list.length,

          packId: list[0].type_id,
          itemPrice: list[0].price,
          itemMinute: list[0].minute,
          itemTitle: list[0].fee_title,
        });

        if (that.data.rfid != '') {
          that.setData({
            goods_id: list[0].id,
            maxNum: 99
          });
        }
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  delete() {
    this.setData({
      noPower: true,
      loan: true,
      freeFail: true,
      model: ''
    });
  },

  hide() {
    this.setData({
      sterilize: true,
      model: ''
    });
  },

  //选择无人柜
  chooseCar(e) {
    console.log(e);
    let that = this;
    let status = e.currentTarget.dataset.status;
    let electric = e.currentTarget.dataset.electric;
    let warning = e.currentTarget.dataset.warning;
    let device = e.currentTarget.dataset.device;
    let id = e.currentTarget.dataset.id;
    let isband = e.currentTarget.dataset.isband;
    let disinfect = e.currentTarget.dataset.disinfect;
    let index = e.currentTarget.dataset.index;
    that.setData({
      packIndex: index,

      packId: e.currentTarget.dataset.packid,
      itemPrice: e.currentTarget.dataset.itemprice,
      itemMinute: e.currentTarget.dataset.itemminute,
      itemTitle: e.currentTarget.dataset.itemtitle,
    });

    if (isband == 0) {
      app.toast("暂无套餐!");
      that.setData({
        id: '',
        device: ''
      });
    } // else if (status == 1 && parseFloat(electric) < parseFloat(warning)) {
    //   that.setData({
    //     model:'no_power',
    //     id: '',
    //     device: ''
    //   })
    // } else if (status == 0 && parseFloat(electric) < parseFloat(warning)) {
    //   that.setData({
    //     model:'no_power',
    //     id: '',
    //     device: ''
    //   })
    // } 
    else if (status == 2) {
        that.setData({
          model: 'has_borrowed',
          device: '',
          id: ''
        });
      } else if (disinfect == 1) {
        that.setData({
          model: 'is_disinfection',
          id: id,
          device: device
        });
      } else if (that.data.wx_credit == 0) {
        app.wxRequest('startRent', {
          'token': wx2my.getStorageSync('token'),
          'device_id': device,
          'goods_id': that.data.goods_id ? that.data.goods_id : '',
          'toy_id': id,
          'num': that.data.num,
          'pack_id': that.data.packId,
          'type': 2
        }, function (res) {
          console.log(res);

          if (res.data.code == 1) {
            let trade_id = res.data.data.trade_id;
            wx2my.navigateTo({
              url: '/pages/pay_deposit/pay_deposit?trade_id=' + trade_id
            });
          } else {
            app.toast(res.data.msg);
          }
        });
      } else {
        that.setData({
          device: device,
          id: id
        });
      }
  },

  endDisinfect() {
    let that = this;
    that.setData({
      endDisinfect: '',
      model: ''
    });

    if (that.data.wx_credit == 0) {
      app.wxRequest('startRent', {
        'token': wx2my.getStorageSync('token'),
        'device_id': that.data.device,
        'toy_id': that.data.id,
        'goods_id': that.data.goods_id ? that.data.goods_id : '',
        'num': that.data.num,
        'pack_id': that.data.packId,
        'type': 2
      }, function (res) {
        console.log(res);

        if (res.data.code == 1) {
          let trade_id = res.data.data.trade_id;
          wx2my.navigateTo({
            url: '/pages/pay_deposit/pay_deposit?trade_id=' + trade_id
          });
          that.setData({
            endDisinfect: 'endDisinfect'
          });
        } else {
          app.toast(res.data.msg);
          that.setData({
            endDisinfect: 'endDisinfect'
          });
        }
      });
    } else {
      that.setData({
        endDisinfect: 'endDisinfect'
      });
    }
  },

  // 同意规则
  bindAcceptRule: function (e) {
    let that = this;
    that.data.acceptRule = !that.data.acceptRule;

    if (that.data.acceptRule == true) {
      that.data.acceptRule = true;
    } else {
      that.data.acceptRule = false;
    }
  },

  //微信支付分授权
  impower() {
    console.log(111);
    let that = this;

    if (that.data.device == '') {
      app.toast("当前柜子尚未绑定无人柜");
      return;
    }

    if (that.data.acceptRule) {
      that.setData({
        impower: ''
      });
      wx2my.showLoading({
        title: '加载中'
      });
      app.wxRequest('startRent', {
        'token': wx2my.getStorageSync('token'),
        'device_id': that.data.device,
        'goods_id': that.data.goods_id ? that.data.goods_id : '',
        // 'toy_id': that.data.id,
        'type': 2,
        'pack_id': that.data.packId,
        'num': that.data.num
      }, function (res) {
        wx2my.hideLoading();
        console.log(res);

        if (res.data.code == 1) {
          let trade_id = res.data.data.trade_id;
          that.setData({
            trade_id: trade_id
          });

          if (that.data.num != 1) {
            that.setData({
              model: 'more_num',
              impower: 'impower'
            });
            return;
          }

          my.tradePay({
            orderStr: res.data.data.orderStr, // 完整的支付参数拼接成的字符串，从 alipay.fund.auth.order.app.freeze 接口获取
            success: (res) => {
              //检查是否授权成功

              app.wxRequest('checkServer_isok', {
                'trade_id': trade_id
              }, function (res) {
                console.log(res);

                if (res.data.code == 100) {
                  //订单创建成功
                  that.get_pull();
                } else {
                  that.setData({
                    model: 'free_fail',
                    impower: 'impower'
                  });
                }
              });
            },
            fail: (res) => {
              that.setData({
                model: 'free_fail',
                impower: 'impower'
              });
            }
          });



        } else if (res.data.code == 40001) {
          let trade_id = res.data.data.trade_id;
          that.setData({
            trade_id: trade_id
          });
          that.toDeposit();
        } else if (res.data.code == 40002) {
          // 特殊用户开柜
          let trade_id = res.data.data.trade_id;
          that.setData({
            trade_id: trade_id
          });
          that.get_pull();
        } else {
          app.toast(res.data.msg);
          that.setData({
            impower: 'impower'
          });
        }
      });
    } else {
      app.toast("请同意委托扣款授权书");
    }
  },

  //缴纳租赁费用
  toDeposit() {
    let that = this;
    that.setData({
      model: ''
    });
    wx2my.navigateTo({
      url: '/pages/pay_deposit/pay_deposit?trade_id=' + that.data.trade_id
    });
  },

  //轮询是否开门成功
  get_pull() {
    let that = this;
    wx2my.showLoading({
      title: '开柜中'
    });
    app.wxRequest('polling_door', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.trade_id
    }, function (res) {
      if (res.data.code == 1) {
        let remote = res.data.data.remote;
        that.setData({
          model: 'open_timeout',
          remote_id: res.data.data.remote_id,
          delay_time: res.data.data.delay_time,
          remote: remote
        });

        if (remote == 0) {
          wx2my.hideLoading();
          app.toast("开柜成功！");
          setTimeout(() => {
            wx2my.reLaunch({
              url: '/pages/home/home'
            });
          }, 5000);
        }
      } else if (res.data.code == 0) {
        wx2my.showLoading({
          title: '开柜中',
          mask: true
        });
        setTimeout(function () {
          that.get_pull();
        }, 2000);
      } else if (res.data.code == -10) {
        that.setData({
          model: 'door_openFail'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -33) {
        that.setData({
          model: 'open_timeout'
        });
        wx2my.hideLoading();
      } else {
        app.toast(res.data.msg);
        wx2my.hideLoading();
      }
    });
  },

  //柜门打开成功
  success() {
    let that = this;

    if (that.data.remote == 0) {
      that.setData({
        model: 'sure_handle'
      });
    } else {
      that.setData({
        model: ''
      });
      wx2my.reLaunch({
        url: '/pages/home/home'
      });
    }
  },

  //开门超时
  doorFail() {
    let that = this;
    if (that.data.onOff) return false;
    that.setData({
      onOff: 1,
      type: 1,
      model: ''
    });
    that.get_doorStatus();
  },

  doorSus() {
    let that = this;
    if (that.data.onOff) return false;
    that.setData({
      onOff: 1,
      type: 2,
      model: ''
    });
    that.get_doorStatus();
  },

  //取出手柄的时候点击重新开柜
  openAgain() {
    let that = this;
    that.setData({
      openAgain: '',
      model: '',
      type: 1
    });
    that.get_doorStatus();
  },

  get_doorStatus() {
    let that = this;
    app.wxRequest('signal_bad_handle', {
      'token': wx2my.getStorageSync('token'),
      'tradeid': that.data.trade_id,
      'type': that.data.type
    }, function (res) {
      console.log(res);

      if (that.data.type == 1) {
        if (res.data.code == 100) {
          if (that.data.remote == 0) {
            that.setData({
              model: 'open_timeout',
              onOff: 0
            });
            setTimeout(() => {
              that.setData({
                model: 'sure_handle'
              });
            }, 2000);
          } else {
            that.setData({
              model: 'open_timeout',
              onOff: 0
            });
          }
        } else if (res.data.code == -100) {
          app.toast(res.data.msg);
          that.setData({
            model: 'door_openFail',
            onOff: 0
          });
        } else {
          app.toast(res.data.msg);
          setTimeout(() => {
            wx2my.reLaunch({
              url: '/pages/home/home'
            });
          }, 2000);
        }

        that.setData({
          openAgain: 'openAgain'
        });
      } else if (that.data.type == 2) {
        wx2my.reLaunch({
          url: '/pages/home/home'
        });
      }
    });
  },

  ysure() {
    this.setData({
      toSure: true,
      type: 2
    });
    this.get_doorStatus();
  },

  del() {
    wx2my.reLaunch({
      url: '/pages/home/home'
    });
  },

  failOpenagain() {
    let that = this;
    if (that.data.onOff) return false;
    that.setData({
      onOff: 1
    });
    app.wxRequest('reopen_door', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.trade_id
    }, function (res) {
      console.log(res);

      if (res.data.code == 100) {
        that.setData({
          model: 'open_timeout',
          onOff: 0
        });
      } else if (res.data.code == -100) {
        app.toast(res.data.msg);
        that.setData({
          model: 'door_openFail',
          onOff: 0
        });
      } else if (res.data.code == -33) {
        app.toast(res.data.msg);
        that.setData({
          model: 'open_timeout',
          onOff: 0
        });
      } else {
        app.toast(res.data.msg);
        setTimeout(() => {
          wx2my.reLaunch({
            url: '/pages/home/home'
          });
        }, 2000);
      }
    });
  },

  toAgree() {
    let that = this;
    wx2my.navigateTo({
      url: '/pages/letter/letter'
    });
  },

  //事件处理函数

  /*点击减号*/
  bindMinus() {
    var num = this.data.num;

    if (num > 1) {
      num--;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*点击加号*/
  bindPlus() {
    var num = this.data.num;
    console.log(num);

    if (num < this.data.maxNum) {
      num++;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*输入框事件*/
  bindManual(e) {
    var num = e.detail.value;
    console.log(e);

    if (num > this.data.maxNum) {
      num = this.data.maxNum;
    }

    if (num < 1) {
      num = 1;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},
  onReachBottom: function () {},
  onShareAppMessage: function () {}
});